import os
import re

from pt1.assert_vd import assert_camera


def natural_sort_key(s):
    return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', s)]


def filter_and_remove_files(directory, roi_bl, all_db_path, ):
    """
    摄像头！！！！！！！
    遍历目录中的文件，并根据时间戳保留最大的文件，删除其余文件。
    如果最终目录内的文件不是刚好等于20个，则清空目录并再次调用assert_camera函数，然后递归调用本函数。
    :param directory: 要遍历的目录路径
    """
    # 获取所有.jpg文件并自然排序
    jpg_files = [f for f in os.listdir(directory) if f.lower().endswith('.jpg')]
    jpg_files.sort(key=natural_sort_key)

    time_list = []

    # 解析文件名中的时间戳
    for frame_filename in jpg_files:
        match = re.search(r'time_(\d+)\.(\d+)\.jpg', frame_filename)
        if match:
            integer_part = int(match.group(1))
            decimal_part = int(match.group(2))
            time_list.append((integer_part, decimal_part, frame_filename))

    # 按照时间戳排序
    time_list.sort()

    # 用于存储需要保留的文件名
    keep_files = set()
    n = len(time_list)

    i = 0
    while i < n:
        max_time = time_list[i]
        j = i + 1
        # 小于3，4也可以，后期调试再看
        while j < n and (time_list[j][0] - time_list[i][0]) <= 4:
            if time_list[j][0] > max_time[0] or (time_list[j][0] == max_time[0] and time_list[j][1] > max_time[1]):
                max_time = time_list[j]
            j += 1

        # 将最大时间戳对应的文件名加入保留集合
        keep_files.add(max_time[2])

        # 更新i为j，跳过已经处理过的文件
        i = j

    # 删除不在keep_files中的文件
    for frame_filename in os.listdir(directory):
        if frame_filename.lower().endswith('.jpg'):
            file_path = os.path.join(directory, frame_filename)
            if frame_filename not in keep_files:
                os.remove(file_path)
                print(f"删除图片: {frame_filename}")
            else:
                print(f"保留文件: {frame_filename}")

    # 检查目录内剩余的.jpg文件数量是否为20
    remaining_jpg_files = [f for f in os.listdir(directory) if f.lower().endswith('.jpg')]
    if len(remaining_jpg_files) != 20:
        print("文件数量不是20个，清空目录并重新调用assert_camera函数")
        # 清空目录
        for frame_filename in remaining_jpg_files:
            file_path = os.path.join(directory, frame_filename)
            os.remove(file_path)
            print(f"删除图片: {frame_filename}")

        # 调用assert_camera函数
        assert_camera(roi=roi_bl, target_dir_path=all_db_path)

        # 递归调用filter_and_remove_files
        filter_and_remove_files(directory, roi_bl, all_db_path)
    else:
        print("文件数量正确，无需进一步操作")


def filter_and_keep_minimum_continuous_frames(directory):
    """
    在给定的目录中，自动检测连续帧区间，并保留每个连续区间内最小时间戳的那一帧。
    如果是单个非连续的文件、连续数小于等于10的文件或文件名数字部分小于150的文件，则删除这些文件。
    :param directory: 要遍历的目录路径
    """
    # 获取所有.jpg文件并自然排序
    jpg_files = [f for f in os.listdir(directory) if f.lower().endswith('.jpg')]
    jpg_files.sort(key=natural_sort_key)

    time_list = []

    # 解析文件名中的时间戳
    for frame_filename in jpg_files:
        match = re.search(r'time_(\d+)\.(\d+)\.jpg', frame_filename)
        if match:
            integer_part = int(match.group(1))
            decimal_part = int(match.group(2))
            timestamp = float(f"{integer_part}.{decimal_part:05d}")

            # 如果文件名数字部分小于150，跳过该文件
            if integer_part < 150:
                continue

            time_list.append((timestamp, frame_filename))

    # 按照时间戳排序
    time_list.sort()

    # 如果没有匹配的文件，直接返回
    if not time_list:
        print("未找到符合条件的文件")
        return

    keep_files = set()
    n = len(time_list)

    i = 0
    while i < n:
        start_index = i
        # 找到当前连续序列的结束位置
        while i + 1 < n and abs(time_list[i + 1][0] - time_list[i][0] - 1) < 1e-5:
            i += 1

        # 计算当前连续序列的长度
        sequence_length = i - start_index + 1

        # 如果是单个非连续文件或连续数小于等于7的序列，跳过不保留
        if sequence_length == 1 or sequence_length <= 10:
            i += 1
            continue

        # 保留连续序列中时间戳最小的那一帧
        keep_files.add(time_list[start_index][1])

        i += 1

    # 删除不在keep_files中的文件
    for frame_filename in os.listdir(directory):
        if frame_filename.lower().endswith('.jpg'):
            if frame_filename not in keep_files:
                file_path = os.path.join(directory, frame_filename)
                os.remove(file_path)
                print(f"删除图片: {frame_filename}")
            else:
                print(f"保留文件: {frame_filename}")




if __name__ == '__main__':
    # filter_and_remove_files(roi_bl=(0, 786, 960, 294), directory='/Users/zltest/testing_video_process/will_assert/wired_720',
    #                         all_db_path= '/Users/zltest/testing_video_process/static/wired_720')
    filter_and_keep_minimum_continuous_frames('/Users/zltest/testing_video_process/green_word/wired_720')